using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;

using RSM.Business;
using RSM.Controls;
using Microsoft.SharePoint.Administration;
namespace RSM.Exporter
{
    [Guid("6d881505-3c19-47f6-8009-11feba19b97a")]
    public class RSMExporter : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        UserControl control = null;
        TextBox txtColumnFeatureName = null;
        TextBox txtColDesc = null;
        TextBox txtContentFeatureName = null;
        TextBox txtContentDesc = null;
        DropDownList ddlColScope = null;
        DropDownList ddlContentScope = null;
        Button btnCreateFeature = null;
        [Persisted]
        List<Fields> fileds = new List<Fields>();
        ListBox listFields = null;
        Label lblContentTypeName = null;
        Label lblPageLayoutName = null;
        Label lblContntType = null;
        TextBox txtPagelayout = null;
        Button btnPagelayouts = null;

        ListBoxExtender listBoxExtender = new ListBoxExtender();
        ExtendedLabelControl labelTitle = new ExtendedLabelControl();
        PageLayoutName pageLayoutName = new PageLayoutName();
        PageLayoutName doubleLabelExtender = new PageLayoutName();
        PageLayoutName pagelayoutFeatureName = new PageLayoutName();
        DropDownList ddlContentTypes = null;
        ExporterManager exporterManager = new ExporterManager();
          
        // CheckBox chkPageLayout = null;

        public RSMExporter()
        {
            this.ExportMode = WebPartExportMode.All;
        }
        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {
                    base.CreateChildControls();
                    listFields = new ListBox();
                    listFields.ID = "listFields";
                    listFields.SelectionMode = ListSelectionMode.Multiple;
                    listFields.EnableViewState = true;
                    this.Controls.Add(listFields);

                    labelTitle.Text = "Select fields which you want to render.";

                    lblPageLayoutName = new Label();
                    lblPageLayoutName.ID = "lblPageLayoutName";
                    this.Controls.Add(lblPageLayoutName);

                    lblContntType = new Label();
                    lblContntType.ID = "lblContntType";
                    this.Controls.Add(lblContntType);

                    txtPagelayout = new TextBox();
                    lblContntType.ID = "txtPagelayout";
                    this.Controls.Add(lblContntType);

                    lblContentTypeName = new Label();
                    lblContentTypeName.ID = "lblContentTypeName";
                    this.Controls.Add(lblContentTypeName);

                    control = Page.LoadControl(@"/_controltemplates/Exporter.ascx") as UserControl;
                    txtColDesc = control.FindControl("txtColumnDesc") as TextBox;
                    txtColumnFeatureName = control.FindControl("txtColumnFeatureName") as TextBox;
                    txtContentDesc = control.FindControl("txtContentDesc") as TextBox;
                    txtContentFeatureName = control.FindControl("txtContentFeatureName") as TextBox;
                    ddlColScope = control.FindControl("ddlColumnScope") as DropDownList;
                    ddlContentScope = control.FindControl("ddlContentScope") as DropDownList;
                    btnCreateFeature = control.FindControl("btnExport") as Button;
                    btnCreateFeature.Click += new EventHandler(btnCreateFeature_Click);
                    // chkPageLayout = control.FindControl("chkCreatePage") as CheckBox;

                    btnPagelayouts = new Button();
                    btnPagelayouts.Text = "Create Page Layouts Feature";
                    btnPagelayouts.ID = "btnPagelayouts";
                    btnPagelayouts.Click += new EventHandler(btnPagelayouts_Click);

                    ddlContentTypes = new DropDownList();
                    ddlContentTypes.ID = "ddlContentTpes";
                    ddlContentTypes.AutoPostBack = true;
                    ddlContentTypes.Visible = false;
                    ddlContentTypes.SelectedIndexChanged += new EventHandler(ddlContentTypes_SelectedIndexChanged);
                    this.Controls.Add(ddlContentTypes);

                    this.Controls.Add(pageLayoutName);
                    this.Controls.Add(listBoxExtender);
                    this.Controls.Add(labelTitle);
                    this.Controls.Add(control);
                    this.Controls.Add(doubleLabelExtender);
                    this.Controls.Add(btnPagelayouts);
                    this.Controls.Add(pagelayoutFeatureName);
                    ToggleControls(false);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        void ddlContentTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            ToggleControls(true);
            listBoxExtender.Items.Clear();
             fileds = exporterManager.GetContentTypeFields(ddlContentTypes.SelectedItem.Text);
            for (int i = 0; i < fileds.Count; i++)
            {
                if (fileds[i].Type != "pageName" && fileds[i].Type != "contentTypeID")
                {
                    string fieldType = fileds[i].Type + "_" + i;
                    listBoxExtender.Items.Add(new ListItem(fileds[i].FieldName, fieldType));
                }
            }
            // listBoxExtender.DataCollection = fileds;
            //listBoxExtender.BindData();
            doubleLabelExtender.Title = "ContentType ID";
            pageLayoutName.Title = "Enter page layout name.";
            pagelayoutFeatureName.Title = "Enter page layout feature name.";
            if (fileds != null)
            {
                foreach (Fields fC in fileds)
                {
                    if (fC.Type == "pageName")
                    {
                        pageLayoutName.PagelayoutText = fC.FieldName;
                    }
                    if (fC.Type == "contentTypeID")
                    {
                        doubleLabelExtender.PagelayoutText = fC.FieldName;
                    }
                }
            }
            //throw new NotImplementedException();
        }
        void btnPagelayouts_Click(object sender, EventArgs e)
        {
            DatabaseReader dbReader = new DatabaseReader();
            List<Fields> selectedFields = new List<Fields>();
            foreach (ListItem item in listBoxExtender.Items)
            {
                if (item.Selected)
                {
                    int itemVal = item.Value.LastIndexOf("_");
                    string itemValue = item.Value.Remove(itemVal);
                    selectedFields.Add(new Fields { Type = itemValue, FieldName = item.Text });
                }
            }
            selectedFields.Add(new Fields { Type = "pageName", FieldName = pageLayoutName.PagelayoutText });
            selectedFields.Add(new Fields { Type = "contentTypeID", FieldName = doubleLabelExtender.PagelayoutText });
            exporterManager.CreatePageLayout(pagelayoutFeatureName.PagelayoutText, selectedFields);
           //throw new NotImplementedException();
        }
        void btnCreateFeature_Click(object sender, EventArgs e)
        {
            List<Fields> fileds = new List<Fields>();

            fileds = exporterManager.GenerateXml(txtColumnFeatureName.Text, txtContentFeatureName.Text, txtColDesc.Text, txtContentDesc.Text, "Site", "Site");

            ddlContentTypes.Visible = true;
            ddlContentTypes.Items.Clear();
            ddlContentTypes.Items.Add(new ListItem("--Select Content Type--"));

            listBoxExtender.Items.Clear();
            foreach (Fields fc in fileds)
            {
                if (fc.Type == "pageName")
                {
                    ddlContentTypes.Items.Add(new ListItem(fc.FieldName));
                }
            }
            if (ddlContentTypes.SelectedIndex == 0)
            {
                ToggleControls(false);
            }
            // listBoxExtender.DataCollection = fileds;
            //listBoxExtender.BindData();
            //doubleLabelExtender.Title = "ContentType ID";
            //pageLayoutName.Title = "Enter PageLayout Name.";
            //pagelayoutFeatureName.Title = "Enter page layout feature name";
            //if (fileds != null)
            //{
            //    foreach (Fields fC in fileds)
            //    {
            //        if (fC.Type == "pageName")
            //        {
            //            pageLayoutName.PagelayoutText = fC.FieldName;
            //        }
            //        if (fC.Type == "contentTypeID")
            //        {
            //            doubleLabelExtender.PagelayoutText = fC.FieldName;
            //        }

            //    }

            //}
            //throw new NotImplementedException();
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }
        public override void RenderControl(HtmlTextWriter writer)
        {
            writer.Write("<table>");
            writer.Write("<tr>");
            writer.Write("<td>");
            control.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            ddlContentTypes.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            pagelayoutFeatureName.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            pageLayoutName.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            doubleLabelExtender.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            labelTitle.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            listBoxExtender.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>");
            btnPagelayouts.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("</table>");

            //base.RenderControl(writer);
        }
        private void ToggleControls(bool visibility)
        {
            pagelayoutFeatureName.Visible = visibility;
            pageLayoutName.Visible = visibility;
            doubleLabelExtender.Visible = visibility;
            labelTitle.Visible = visibility;
            listBoxExtender.Visible = visibility;
            btnPagelayouts.Visible = visibility;
        }
        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}
